package com.taotao.tools.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.StringUtils;
import com.taotao.tools.core.str.MoneyUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * excel导入自定义Decimal转换类
 *
 * @author likailang
 * @date 2021-05-25
 */
public class BigDecimalConverter implements Converter<BigDecimal> {
    @Override
    public Class supportJavaTypeKey() {
        return BigDecimal.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }


    @Override
    public BigDecimal convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                        GlobalConfiguration globalConfiguration) throws Exception {
        if (StringUtils.isEmpty(cellData.getStringValue())) {
            return null;
        }
        return new BigDecimal(cellData.getStringValue());
    }




    @Override
    public WriteCellData<?> convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) throws Exception {

        return new WriteCellData(MoneyUtil.formatMoney(value.setScale(2, RoundingMode.HALF_UP)));
    }

}
